<?php 
$cs=Yii::app()->getClientScript();
$cs->registerCssFile($cs->getCoreScriptUrl().'/jui/css/base/jquery-ui.css');
$cs->registerScriptFile($cs->getCoreScriptUrl().'/jui/js/jquery-ui.min.js');
?>
<style type="text/css">
#layouts {border:1px solid #AAAAAA;}
.scroll-pane { overflow: auto; width: 99%; float:left; }
.scroll-content { width: 2440px; float: left; background-color: #ffffff;}
.scroll-content .empty {display: block; text-align: center; padding: 20px 0;}
.scroll-content-item { width: 230px; height: 260px; float: left; margin: 10px; text-align: center; }
* html .scroll-content-item { display: inline; } /* IE6 float double margin bug */
.scroll-content-item .wrapper-img {
     background: url("/themes/Admin/images/thumb-border-230x190.jpg") no-repeat scroll 0 0 transparent;
    float: left;
    height: 220px;
    list-style: none outside none;
    width: 230px;
}
.scroll-content-item .name {text-align: center; font-size: 12px;}
.scroll-content-item a.img {
    display: table-cell; vertical-align: middle; height: 218px; width: 230px; text-align: center;
}
.scroll-content-item a img {border: medium none;}
.scroll-bar-wrap { clear: left; padding: 0 4px 0 2px; margin: 0 -1px -1px -1px; }
.scroll-bar-wrap .ui-slider { background: none; border:0; height: 2em; margin: 0 auto;  }
.scroll-bar-wrap .ui-handle-helper-parent { position: relative; width: 100%; height: 100%; margin: 0 auto; }
.scroll-bar-wrap .ui-slider-handle { top:.2em; height: 1.5em; }
.scroll-bar-wrap .ui-slider-handle .ui-icon { margin: -8px auto 0; position: relative; top: 50%; }
.row.extra div label {width: auto; float: none; text-align: left; display: inline;}
</style>
<script type="text/javascript">
$(function() {
    $.fn.initPane = function() {
        //scrollpane parts
        var scrollPane = $( ".scroll-pane" ),
            scrollContent = $( ".scroll-content" );
            
        var item_size = $('.scroll-content-item').size();
        var item_width = $('.scroll-content-item:first').width()+20;
        width = item_width*item_size;
        scrollContent.width(width);
        var max = width - scrollPane.width();
        
        //build slider
        var scrollbar = $( ".scroll-bar" ).slider({
            slide: function( event, ui ) {
                if ( scrollContent.width() > scrollPane.width() ) {
                    scrollContent.css( "margin-left", '-'+ui.value + "px" );
                } else {
                    scrollContent.css( "margin-left", 0 );
                }
            }, 
            stop: function (event, ui) {
                    scrollContent.animate({ 'margin-left' : '-'+ui.value + 'px' }, 500, 'linear');
            },
            max : max,
            animate : 700
        });
        
        //append icon to handle
        var handleHelper = scrollbar.find( ".ui-slider-handle" )
        .mousedown(function() {
            scrollbar.width( handleHelper.width() );
        })
        .mouseup(function() {
            scrollbar.width( "100%" );
        })
        .append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
        .wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
        
        //change overflow to hidden now that slider handles the scrolling
        scrollPane.css( "overflow", "hidden" );
        
        //size scrollbar and handle proportionally to scroll distance
        function sizeScrollbar() {
            var remainder = scrollContent.width() - scrollPane.width();
            if (remainder <= 20)
            {
                scrollbar.hide();
                return;
            }
            scrollbar.show();
            var proportion = remainder / scrollContent.width();
            var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
            scrollbar.find( ".ui-slider-handle" ).css({
                width: handleSize,
                "margin-left": -handleSize / 2
            });
            handleHelper.width( "" ).width( scrollbar.width() - handleSize );
        }
        
        //reset slider value based on scroll content position
        function resetValue() {
            var remainder = scrollPane.width() - scrollContent.width();
            var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
                parseInt( scrollContent.css( "margin-left" ) );
            var percentage = Math.round( leftVal / remainder * 250 );
            scrollbar.slider( "value", percentage );
        }
        
        //if the slider is 100% and window gets larger, reveal content
        function reflowContent() {
                var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
                var gap = scrollPane.width() - showing;
                if ( gap > 0 ) {
                    scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
                }
        }
        
        //change handle position on window resize
        $( window ).resize(function() {
            resetValue();
            sizeScrollbar();
            reflowContent();
        });
        //init scrollbar size
        setTimeout( sizeScrollbar, 10 );//safari wants a timeout
    }
    $.fn.initPane();
    parent.$('#sb-nav-save-form').parent().hide();
});
</script>
<?php
$script = "
jQuery.fn.load_widget_data = function(widget_id, widget_layout_id, page_id){
    jQuery.get('".$this->createUrl('/Core/service/ajax', array('SID'=>'Cms.widgetData.getList'))."', {'status' : 1, 'widget_id' : widget_id, 'widget_layout_id' : widget_layout_id, 'page_id' : page_id}, function(res){
        res = eval(res);
        if (res.models.length)
        {
            jQuery('.extra input:eq(1)').removeAttr('disabled');
            jQuery('#PageWidget_widget_data_id option:gt(0)').remove();
            var options = [];
            for (var i in res.models)
            {
                options.push('<option value=\"'+res.models[i].id+'\">'+res.models[i].name+'</option>');
            }
            jQuery('#PageWidget_widget_data_id').append(options.join(''));
            jQuery('html, body').animate({scrollTop: jQuery('.extra').offset().top}, 1000);
        }
        else
        {
            jQuery('.extra input:eq(0)').trigger('click');
            jQuery('.extra input:eq(1)').attr('disabled', 'disabled');
        }
    });
}

jQuery('body').delegate('.scroll-content-item a', 'click', function(){
    var matches = jQuery(this).attr('class').match(/widget_id_(\d+) widget_layout_id_(\d+)/);
    if (matches.length == 3)
    {
        jQuery('.scroll-content-item').removeClass('selected');
        jQuery(this).closest('.scroll-content-item').addClass('selected');
        var widget_id = parseInt(matches[1]);
        var widget_layout_id = parseInt(matches[2]);
        jQuery('#widget_id').val(widget_id);
        jQuery('#PageWidget_widget_layout_id').val(widget_layout_id);
        
        //load pages
        jQuery.get('".$this->createUrl('/Core/service/ajax', array('SID'=>'Cms.page.getListByWidgetLayout'))."', {widget_layout_id : widget_layout_id}, function(res){
            res = eval(res);
            if (res.models.length)
            {
                jQuery('.extra input:eq(1)').removeAttr('disabled');
                jQuery('#used_in_page option:gt(0)').remove();
                var options = [];
                for (var i in res.models)
                {
                    options.push('<option value=\"'+res.models[i].id+'\">'+res.models[i].title+'</option>');
                }
                jQuery('#used_in_page').append(options.join(''));
                jQuery('html, body').animate({scrollTop: jQuery('.extra').offset().top}, 1000);
            }
            else
            {
                jQuery('.extra input:eq(0)').trigger('click');
                jQuery('.extra input:eq(1)').attr('disabled', 'disabled');
            }
        });
        
        //load widget data
        jQuery.fn.load_widget_data(widget_id, widget_layout_id, 0);
        
        jQuery('.form').show();
    }
    return false;
});

jQuery('body').delegate('#used_in_page', 'change', function(){
    var widget_id = jQuery('#widget_id').val();
    var widget_layout_id = jQuery('#PageWidget_widget_layout_id').val();
    var page_id = jQuery(this).val();
    jQuery.fn.load_widget_data(widget_id, widget_layout_id, page_id);
});

jQuery('#copy_data').click(function(){
    var row = jQuery('#instacne_name').closest('.row');
    if (jQuery(this).attr('checked'))
        row.show();
    else
        row.hide();
});

jQuery('.extra input').click(function(){
    var value = parseInt(jQuery(this).val());
    var row = jQuery('.existing');
    if (value == 1)
    {
        row.show();
        jQuery('html, body').animate({scrollTop: jQuery('.existing').offset().top}, 1000);
    }
    else
        row.hide();
});
";
$cs->registerScript(__CLASS__.'#SelectWidgetLayout', $script);

$script = "
jQuery('.filters select').change(function(){
    var widget_id = jQuery('#filter_widget_id').val();
    if (widget_id == '')
        widget_id = 0;
    else
        widget_id = parseInt(widget_id);
    var type = jQuery('#filter_type').val();
    if (type == '')
        type = 0;
    else
        type = parseInt(type);
    jQuery.fn.yiiListView.update('layouts', {
        data : {widget_id : widget_id, type : type}
    })
});
";
$cs->registerScript(__CLASS__.'#Filters', $script);

$this->widget('zii.widgets.CListView', array(
    'id'=>'layouts',
    'dataProvider'=>$dataProvider,
    'itemView'=>'_layout_item',
    'template'=>'{items}<div class="scroll-bar-wrap ui-widget-content ui-corner-bottom"><div class="scroll-bar"></div></div>',
    'htmlOptions'=>array(
        'class'=>'scroll-pane ui-widget ui-corner-all',
//        'style'=>'width:500px;',
    ),
    'itemsCssClass'=>'scroll-content',
    'afterAjaxUpdate'=>'js:function(){jQuery.fn.initPane();if (jQuery(".scroll-content .empty").size()) jQuery(".scroll-content").css({width: "100%"}).removeClass(".scroll-content");}',
));?>
<div style="clear: both;"></div>
<p class="filters">
    <label>Filter by:</label>
    <?php echo CHtml::dropDownList('filter_type', '', $types, array('prompt'=>'---All---'));?>
    <?php echo CHtml::dropDownList('filter_widget_id', '', $widgets, array('prompt'=>'---Select Widget---'));?>
</p>
<div class="form wide" style="display: none;">
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'page-widget-form',
	'enableClientValidation'=>true,
)); ?>
    <?php echo $form->hiddenField($model, 'status');?>
    <?php echo $form->hiddenField($model, 'page_id');?>
    <?php echo $form->hiddenField($model, 'revision_id');?>
    <?php echo $form->hiddenField($model, 'container');?>
    <?php echo $form->hiddenField($model, 'widget_layout_id');?>
    <?php echo CHtml::hiddenField('widget_id');?>
    
    <div class="row extra">
        <label>&nbsp;</label>
        <div>
            <?php echo CHtml::radioButtonList('action', 0, array('Create new', 'Use existing'), array('separator'=>'')); ?>
        </div>
    </div>
    
    <div class="existing" style="display: none;">
	<div class="row">
        <?php echo CHtml::label('Page', 'used_in_page'); ?>
        <?php echo CHtml::dropDownList('used_in_page', '', array(), array('prompt'=>'---All---')); ?>
    </div>
    
    <div class="row">
		<?php echo $form->labelEx($model,'widget_data_id'); ?>
		<?php echo $form->dropDownList($model,'widget_data_id', array(), array('prompt'=>'---Select instance---')); ?>
		<?php echo $form->error($model,'widget_data_id'); ?>
	</div>

    <div class="row">
        <label>&nbsp;</label>
        <div>
        <?php echo CHtml::checkBox('copy_data', false, array('id'=>'copy_data'));?>
        <?php echo CHtml::label('Create a new instance with the same content', 'copy_data', array('style'=>'float:none;width:auto;display:inline;')); ?>
        </div>
    </div>

    <div class="row" style="display: none;">
        <?php echo CHtml::label('Name', 'instacne_name');?>
        <?php echo CHtml::textField('instacne_name', '', array('size'=>60));?>
    </div>
    </div>

	<div class="row buttons">
		<?php echo CHtml::button('Continue', array('onClick'=>'js:jQuery("form").submit();')); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->